//
//  LeaonWorking.m
//  XhlTrip
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "LeaonWorking.h"
#import "AFNetworking.h"


@implementation LeaonWorking

- (void)getDataWithUrl:(NSString *)urlStr pathname:(NSString *)pathName resultBlock:(void(^)(id result))block
{
    NSLog(@"%@", urlStr);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        block(responseObject);
        
        /* 存文件 */
        
        // 如果网络请求成功  就把文件存成data类型
        NSString *array = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [NSString stringWithFormat:@"%@/%@/%@", array, @"Caches", pathName];
        NSLog(@"存%@", path);
        NSData *dd = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        [dd writeToFile:path atomically:YES];
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        // 如果网络请求失败就读本地文件  然后转化成对象类型  首先判断本地有没有文件 不用判断网络
        NSString *array = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [NSString stringWithFormat:@"%@/%@/%@", array, @"Caches", pathName];
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        if (data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        block(result);
        }
        
    }];
}


/* 网络请求直接带上文件名参数 文件存储  */
+ (void)netWorkingHanderGetGataWithUrl:(NSString *)urlStr pathname:(NSString *)pathName resultBlock:(void(^)(id result))block
{
    LeaonWorking *leaonWork = [[LeaonWorking alloc] init];
    [leaonWork getDataWithUrl:urlStr pathname:pathName resultBlock:block];
}




@end
